<template>
  <view class="">
    <yy-paging
      v-model="dataList"
      @query="queryList"
      ref="paging"
      :auto="automatic"
      class="bg-white"
      @scroll="scroll"
      :refresher-enabled="false"
      @scrolltolower="onScrollToLower"
    >
      <template #top>
        <u-navbar
          back-text=""
          title="切换城市"
          :background="{ backgroundColor: isScroll ? '#FFFFFF' : 'transparent' }"
          :border-bottom="false"
          :custom-style="{ transition: 'background-color 0.3s ease-in-out' }"
        >
        </u-navbar>
        <view class="p-4 pb-0">
          <u-search placeholder="输入城市名称" v-model="keyword" :show-action="false"></u-search>
        </view>
      </template>
      <view class="flex flex-col gap-4 p-4">
        <view class="flex justify-between">
          <view class="flex gap-1 items-center">
            <image src="/static/icon_positioning_fill@3x.png" class="size-4" mode="scaleToFill" />
            <view class="text-[13px] text-[#171B24]">当前定位：{{ city }}</view>
          </view>
          <view class="flex gap-1 items-center" @click="repositioning">
            <image src="/static/iconpunctuationpositioningBrand@3X.png" class="size-4" mode="scaleToFill" />
            <view class="text-[13px] text-[#171B24]">重新定位</view>
          </view>
        </view>
        <!-- 热门城市部分保持不变 -->
        <template v-if="!keyword">
          <view class="text-[13px] text-[#919499]"> 热门城市 </view>
          <view class="grid grid-cols-4 gap-x-1 gap-y-3">
            <view
              class="bg-[#F4F6F8] rounded-[18px] flex justify-center items-center py-1"
              @click="vk.navigateTo('/pages/index/positioning?city=' + ii)"
              v-for="(i, k) in citylist.hotcity.lists"
              :key="k"
            >
              {{ i }}
            </view>
          </view>
          <view class="w-full border-t"> </view>
        </template>

        <!-- 城市列表部分使用过滤后的数据 -->
        <view v-for="(i, k) in filteredCityList" class="flex flex-col gap-4" :key="k" :id="`letter-${i.title}`">
          <view class="text-[13px] text-[#919499]">
            {{ i.title }}
          </view>
          <view v-for="(ii, kk) in i.lists" :key="kk" @click="vk.navigateTo('/pages/index/positioning?city=' + ii)">
            <text class="text-[14px] text-[#171B24]">
              {{ ii }}
            </text>
          </view>
        </view>

        <!-- 无搜索结果时显示提示 -->
        <view v-if="keyword && filteredCityList.length === 0" class="py-8 text-center text-gray-500"> 未找到相关城市 </view>
      </view>
    </yy-paging>
    <view class="flex fixed top-0 right-0 z-50 flex-col justify-center items-center w-4 h-screen">
      <view
        v-for="(i, k) in citylist.city"
        class="text-[13px]"
        :class="currentLetter === i.title ? 'text-[#00A9AB] font-extrabold' : 'text-[#171B24]'"
        :key="k"
        @tap="scrollToLetter(i.title)"
      >
        {{ i.title }}
      </view>
    </view>

    <!-- 中间显示的字母提示 -->
    <view
      v-if="showLetterIndicator"
      class="flex fixed top-1/2 left-1/2 z-50 justify-center items-center w-16 h-16 bg-black bg-opacity-60 rounded-lg transform -translate-x-1/2 -translate-y-1/2"
    >
      <text class="text-3xl text-white">{{ currentLetter }}</text>
    </view>
  </view>
</template>

<script>
  import citylist from '../../common/js/citylist.json'

  export default {
    data() {
      return {
        isScroll: false,
        dataList: [],
        automatic: false,
        keyword: '',
        citylist: citylist,
        currentLetter: '',
        showLetterIndicator: false,
        letterPositions: {},
        observer: null,
        city: ''
      }
    },

    mounted() {
      this.setupIntersectionObserver()
    },
    onLoad(options) {
      // this.city = options.city
      this.repositioning()
    },

    beforeDestroy() {
      // 销毁观察器
      if (this.observer) {
        this.observer.disconnect()
      }
    },

    methods: {
      repositioning() {
        let that = this
        vk.showLoading('定位中...')
        uni.getLocation({
          type: 'gcj02',
          geocode: true,
          success: function (res) {
            that.city = res.address.city
          },
          complete: function () {
            vk.hideLoading()
          }
        })
      },
      scroll(e) {
        this.isScroll = e.detail.scrollTop > 0
        this.detectCurrentLetter(e.detail.scrollTop)
      },

      async queryList(page, limit) {
        this.$refs.paging.complete([1, 1, 1])
      },

      // 设置交叉观察器来检测当前可见的字母区域
      setupIntersectionObserver() {
        setTimeout(() => {
          // 获取所有字母区域的位置信息
          this.citylist.city.forEach(item => {
            const query = uni.createSelectorQuery().in(this)
            query
              .select(`#letter-${item.title}`)
              .boundingClientRect(data => {
                if (data) {
                  this.letterPositions[item.title] = data.top
                }
              })
              .exec()
          })
        }, 500)
      },

      // 根据滚动位置检测当前字母
      detectCurrentLetter(scrollTop) {
        // 找到最接近当前滚动位置的字母
        let closestLetter = ''
        let minDistance = Infinity

        for (const [letter, position] of Object.entries(this.letterPositions)) {
          const distance = Math.abs(position - scrollTop)
          if (distance < minDistance) {
            minDistance = distance
            closestLetter = letter
          }
        }

        if (closestLetter && this.currentLetter !== closestLetter) {
          this.currentLetter = closestLetter
        }
      },

      // 点击字母时滚动到对应位置
      scrollToLetter(letter) {
        this.currentLetter = letter
        this.showLetterIndicator = true

        // 滚动到对应位置
        // uni
        //   .createSelectorQuery()
        //   .in(this)
        //   .select(`#letter-${letter}`)
        //   .boundingClientRect(data => {
        //     if (data) {
        //       // 修改这里，直接使用scrollTo方法滚动到指定位置
        //       this.$refs.paging.scrollTo({
        //         scrollTop: data.top,
        //         duration: 300
        //       })
        //     }
        //   })
        //   .exec()
        let x = `letter-${letter}`
        this.$refs.paging.scrollIntoViewById(x, 100, true)

        // 显示中间的字母提示
        setTimeout(() => {
          this.showLetterIndicator = false
        }, 500)
      },

      onScrollToLower() {
        // 滚动到底部时的处理
      }
    },
    computed: {
      // 根据搜索关键词过滤城市列表
      filteredCityList() {
        if (!this.keyword) {
          return this.citylist.city
        }

        const keyword = this.keyword.toLowerCase()
        return this.citylist.city
          .map(item => {
            return {
              title: item.title,
              lists: item.lists.filter(city => city.toLowerCase().includes(keyword))
            }
          })
          .filter(item => item.lists.length > 0)
      }
    }
  }
</script>

<style lang="scss" scoped>
  page {
    background-color: #fff !important;
  }
</style>
